package org.example.filters;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.example.predicates.MyConfig;
import java.util.Arrays;
import java.util.List;

/**
 * @author control
 * 自定义过滤器的使用： 计算经过网关,服务提供服务的时间
 */
@Component
@Data
public class CalServiceTimeGatewayFilterFactory extends AbstractGatewayFilterFactory<MyConfig> {


    public CalServiceTimeGatewayFilterFactory() {
        super(MyConfig.class);
    }

    @Override
    public GatewayFilter apply(MyConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 进入服务的时间
                long beginTime = System.currentTimeMillis();
                System.out.println("name"+config.getKey());
                System.out.println("value"+config.getValue());

//                return chain.filter(exchange); 服务放行
                return chain.filter(exchange).then(
                        Mono.fromRunnable(()->{
                            System.out.println("服务回调啦！");
                            long endTime = System.currentTimeMillis();
                            System.out.println("time="+(endTime-beginTime));
                        })
                );
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        // 封装配置文件中的值，写入
        return Arrays.asList("key","value");
    }
}
